package com.tqz.juc.sentinel;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2022/3/2 19:23
 */
public class RatelimitTest {
    
    private static long timestamp = System.currentTimeMillis();
    private static long capacity = 10; // 桶的容量
    private static long rate = 2; // 水流出的速率
    private static long water; // 当前剩余多少水(当前累计请求数)
    
    public static void main(String[] args) {
        if (limit()) {
            System.out.println("顺利通过");
        } else {
            System.out.println("限流");
        }
    }
    
    public static boolean limit() {
        long now = System.currentTimeMillis();
        
        water = Math.max(0, water - ((now - timestamp) / 1000) * rate);
        timestamp = now;
        
        if ((water + 1) < capacity) {
            water += 1;
            return true;
        } else {
            return false;
        }
    }
}
